//
//  UUIntentOrderListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 27/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUIntentOrderListVC.h"
#import "UUIntentOrderManager.h"
#import "UUResourceManager.h"
#import "UUUserManager.h"
#import <UUFoundation/UUCityManager.h>
#import "UUPermissionManager.h"
#import "UUBaseTableViewCell.h"
#import "UUIntentOrderDetailVC.h"
#import "UUIntentOrderHistoryListVC.h"
#import "UUIntentOrderBidVC.h"
#import <UUFoundation/UIViewController+ModalTransition.h>

@interface UUIntentOrderListHeaderView : UIView

@property (nonatomic, strong) UIButton *ignoreAllButton;
@property (nonatomic, strong) UILabel *notificationLabel;
@property (nonatomic, strong) UISwitch *notificationSwitch;

@property (nonatomic, copy) void (^ignoreAllBlock)(void);

@end

@implementation UUIntentOrderListHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.ignoreAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.ignoreAllButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.ignoreAllButton setTitle:@"全部忽略" forState:UIControlStateNormal];
        [self.ignoreAllButton setTitleColor:COMMON_TEXT_LIGHT_COLOR forState:UIControlStateNormal];
        self.ignoreAllButton.layer.borderWidth = 1;
        self.ignoreAllButton.layer.cornerRadius = 2;
        self.ignoreAllButton.layer.borderColor = COMMON_TEXT_LIGHT_COLOR.CGColor;
        [self.ignoreAllButton addTarget:self action:@selector(ignoreAll) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.ignoreAllButton];
        [self.ignoreAllButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(82);
            make.left.mas_equalTo(15);
            make.height.mas_equalTo(30);
            make.centerY.mas_equalTo(0);
        }];
        
        self.notificationSwitch = [UISwitch new];
        [self addSubview:self.notificationSwitch];
        [self.notificationSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.centerY.mas_equalTo(0);
        }];
        
        self.notificationLabel = [UILabel new];
        self.notificationLabel.font = [UIFont systemFontOfSize:14];
        self.notificationLabel.text = @"报价提醒";
        self.notificationLabel.textColor = COMMON_TEXT_DARK_COLOR;
        [self addSubview:self.notificationLabel];
        [self.notificationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.notificationSwitch.mas_left).offset(-8);
            make.centerY.mas_equalTo(0);
        }];
    }
    return self;
}

- (void)ignoreAll {
    BLOCK_SAFE_CALLS(self.ignoreAllBlock);
}

@end

/////////////////////////////////////////////////////////////////////////////////

@interface UUIntentOrderCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *daysLabel;
@property (nonatomic, strong) UILabel *arrivalLabel;
@property (nonatomic, strong) UILabel *carNumberLabel;
@property (nonatomic, strong) UILabel *statusLabel;

@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *ignoreButton;

@property (nonatomic, copy) void (^confirmBlock)(void);
@property (nonatomic, copy) void (^ignoreBlock)(void);

@end

@implementation UUIntentOrderCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        self.titleLabel.textColor = COMMON_TEXT_DARK_PURPLE_COLOR;
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(21);
            make.top.mas_equalTo(18);
            make.left.mas_equalTo(15);
        }];
        
        self.timeLabel = [UILabel new];
        [self.contentView addSubview:self.timeLabel];
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleLabel);
            make.top.equalTo(self.titleLabel.mas_bottom).offset(9);
            make.height.mas_equalTo(26);
        }];
        self.daysLabel = [UILabel new];
        [self.contentView addSubview:self.daysLabel];
        [self.daysLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.timeLabel);
            make.top.equalTo(self.timeLabel.mas_bottom);
            make.height.equalTo(self.timeLabel);
        }];
        self.arrivalLabel = [UILabel new];
        [self.contentView addSubview:self.arrivalLabel];
        [self.arrivalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.left.equalTo(self.contentView.mas_centerX).offset(20);
            make.height.equalTo(self.timeLabel);
            make.top.equalTo(self.timeLabel);
        }];
        self.carNumberLabel = [UILabel new];
        [self.contentView addSubview:self.carNumberLabel];
        [self.carNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.arrivalLabel);
            make.height.equalTo(self.timeLabel);
            make.top.equalTo(self.daysLabel);
        }];
        
        self.statusLabel = [UILabel new];
        self.statusLabel.font = [UIFont systemFontOfSize:14];
        self.statusLabel.text = @"进行中";
        self.statusLabel.textColor = COMMON_TEXT_ORANGE_COLOR;
        [self.contentView addSubview:self.statusLabel];
        [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(13);
            make.right.mas_equalTo(-15);
            make.height.mas_equalTo(20);
        }];
        
        self.confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.confirmButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.confirmButton setTitle:@"报价" forState:UIControlStateNormal];
        [self.confirmButton setBackgroundImage:GetResourceManager().buttonImage1 forState:UIControlStateNormal];
        [self.confirmButton setBackgroundImage:GetResourceManager().buttonImage1HL forState:UIControlStateHighlighted];
        [self.confirmButton addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.confirmButton];
        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView.mas_centerX).offset(10);
            make.top.equalTo(self.carNumberLabel.mas_bottom).offset(13);
            make.width.mas_equalTo(75);
            make.height.mas_equalTo(30);
        }];
        
        self.ignoreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.ignoreButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.ignoreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.ignoreButton setTitle:@"忽略" forState:UIControlStateNormal];
        [self.ignoreButton setBackgroundImage:GetResourceManager().buttonImage4 forState:UIControlStateNormal];
        [self.ignoreButton setBackgroundImage:GetResourceManager().buttonImage4HL forState:UIControlStateHighlighted];
        [self.ignoreButton addTarget:self action:@selector(ignore) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.ignoreButton];
        [self.ignoreButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.top.equalTo(self.confirmButton);
            make.left.equalTo(self.confirmButton.mas_right).offset(10);
        }];
        
        if (![GetPermissionManager() checkPermission:UUPermissionFlagOrderReadWrite]) {
            self.confirmButton.enabled = NO;
            self.ignoreButton.enabled = NO;
        }
    }
    
    return self;
}

- (void)confirm {
    BLOCK_SAFE_CALLS(self.confirmBlock);
}

- (void)ignore {
    BLOCK_SAFE_CALLS(self.ignoreBlock);
}

- (void)setupWithModel:(UUIntentOrderModel *)model {
    self.titleLabel.text = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:model.carCategoryId].name;
    
    self.timeLabel.attributedText = [self generateAttributedStringWithTitle:@"时间：" text:[model.departTime formatDateByFormatString:@"yyyy.MM.dd HH:mm"]];
    self.arrivalLabel.attributedText = [self generateAttributedStringWithTitle:@"到达城市：" text:[GetCityManager() fetchCityWithCityId:model.arrival.toAddressModel.cityId].simpleName];
    self.daysLabel.attributedText = [self generateAttributedStringWithTitle:@"天数：" text:[NSString daysToDisplayString:model.days]];
    self.carNumberLabel.attributedText = [self generateAttributedStringWithTitle:@"数量：" text:[NSString stringWithFormat:@"%ld辆", model.carNum]];
    
    self.statusLabel.hidden = !model.isBid;
}

- (NSAttributedString *)generateAttributedStringWithTitle:(NSString *)title text:(NSString *)text {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title ?: @" " attributes:@{
                                                                                                                               NSFontAttributeName : [UIFont systemFontOfSize:14],
                                                                                                                               NSForegroundColorAttributeName : COMMON_TEXT_LIGHT_COLOR
                                                                                                                               }];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text ?: @" " attributes:@{
                                                                                                                  NSFontAttributeName : [UIFont systemFontOfSize:14],
                                                                                                                  NSForegroundColorAttributeName : COMMON_TEXT_BLACK_COLOR
                                                                                                                  }]];
    return attributedString;
}

@end

/////////////////////////////////////////////////////////////////////////////////

@interface UUIntentOrderListVC () <UITableViewDelegate, UITableViewDataSource, UUIntentOrderManagerObserver>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<UUIntentOrderModel *> *orders;
@property (nonatomic, strong) id since;

@property (nonatomic, strong) UIImageView *emptyImageView;

@end

@implementation UUIntentOrderListVC

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"待报价";
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"历史" target:self selector:@selector(enterHistory)];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    self.tableView.rowHeight = 160;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UUIntentOrderCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    WEAK_SELF();
    self.tableView.mj_header = [UURefreshHeader headerWithRefreshingBlock:^{
        [weakSelf loadForFirst];
    }];
    self.tableView.mj_header.hidden = YES;
    
    self.tableView.mj_footer = [UURefreshFooter footerWithRefreshingBlock:^{
        [weakSelf loadMore];
    }];
    self.tableView.mj_footer.hidden = YES;
    
    if ([GetPermissionManager() checkPermission:UUPermissionFlagOrderReadWrite]) {
        UUIntentOrderListHeaderView *headerView = [[UUIntentOrderListHeaderView alloc] initWithFrame:CGRectMake(0, 0, 0, 60)];
        headerView.notificationSwitch.on = [GetUserManager() fetchUserInfo].receiveIntentOrder;
        [headerView.notificationSwitch addTarget:self action:@selector(updateReceiveOrderNotification) forControlEvents:UIControlEventValueChanged];
        [headerView setIgnoreAllBlock:^{
            [UIAlertController presentAlertControllerWithTitle:@"确定忽略全部报价？" message:nil doneBlock:^{
                [weakSelf ignoreAllOrders];
            } cancelBlock:nil];
        }];
        self.tableView.tableHeaderView = headerView;
    }
    
    [self reload];
    
    [GetIntentOrderManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateEmptyImageViewStatus {
    if (self.orders.count == 0) {
        if (self.emptyImageView == nil) {
            self.emptyImageView = [[UIImageView alloc] initWithImage:GetResourceManager().emptyDataImage];
            [self.tableView addSubview:self.emptyImageView];
            [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo(100);
            }];
        }
        
        self.emptyImageView.hidden = NO;
    } else {
        self.emptyImageView.hidden = YES;
    }
}

- (void)updateReceiveOrderNotification {
    UUIntentOrderListHeaderView *header = (UUIntentOrderListHeaderView *)self.tableView.tableHeaderView;
    ShowIndicator();
    WEAK_SELF();
    [GetIntentOrderManager() asyncUpdateIntentOrderReceiveNotification:header.notificationSwitch.on
                                                         completeBlock:^(NSError *error) {
                                                         
                                                             HideIndicatorInView(weakSelf.view);
                                                             if (error != nil) {
                                                                 ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                             } else {
                                                                 GetUserManager().fetchUserInfo.receiveIntentOrder = header.notificationSwitch.on;
                                                             }
                                                         }];
}

- (void)reload {
    ShowIndicator();
    [self loadForFirst];
}

- (void)loadForFirst {
    WEAK_SELF();
    [GetIntentOrderManager() asyncFetchIntentOrdersWithSince:nil
                                                      length:20
                                               completeBlock:^(NSArray<UUIntentOrderModel *> *orders, id since, NSError *error) {
                                                   [weakSelf.tableView.mj_header endRefreshing];
                                                   if (error == nil) {
                                                       HideIndicatorInView(weakSelf.view);
                                                       weakSelf.orders = [orders mutableCopy];
                                                       weakSelf.since = since;
                                                       [weakSelf.tableView reloadData];
                                                       
                                                       if (weakSelf.tableView.mj_header.hidden) {
                                                           weakSelf.tableView.mj_header.hidden = NO;
                                                       }
                                                       
                                                       weakSelf.tableView.mj_footer.hidden = orders.count < 20;
                                                   } else {
                                                       ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                   }
                                                   
                                                   [weakSelf updateEmptyImageViewStatus];
                                               }];
}

- (void)loadMore {
    WEAK_SELF();
    [GetIntentOrderManager() asyncFetchIntentOrdersWithSince:self.since
                                                      length:20
                                               completeBlock:^(NSArray<UUIntentOrderModel *> *orders, id since, NSError *error) {
                                                   if (error == nil) {
                                                       if (orders.count < 20) {
                                                           [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                                                       } else {
                                                           [weakSelf.tableView.mj_footer endRefreshing];
                                                       }
                                                       
                                                       [weakSelf.orders addObjectsFromArray:orders];

                                                       weakSelf.since = since;
                                                       [weakSelf.tableView reloadData];
                                                   } else {
                                                       [weakSelf.tableView.mj_footer endRefreshing];
                                                       ShowTipsOnView(error.localizedDescription, weakSelf.view);
                                                   }
                                               }];
}

- (void)enterHistory {
    [self.navigationController pushViewController:[UUIntentOrderHistoryListVC instanceOfAppropriate] animated:YES];
}

- (void)confirmOrder:(NSNumber *)orderId {
    UUIntentOrderBidVC *bidVC = [UUIntentOrderBidVC instanceOfAppropriate];
    bidVC.intentOrderId = orderId;
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:bidVC];
    [self presentModalViewController:nav];
}

- (void)ignoreAllOrders {
    [self asyncUpdateOrderWithOrderId:nil actionType:UUIntentOrderActionTypeIgnoreAll];
}

- (void)ignoreOrder:(NSNumber *)orderId {
    [UIAlertController presentAlertControllerWithTitle:@"确定忽略该报价？" message:nil doneBlock:^{
        [self asyncUpdateOrderWithOrderId:orderId actionType:UUIntentOrderActionTypeIgnore];
    } cancelBlock:nil];
}

- (void)asyncUpdateOrderWithOrderId:(NSNumber *)orderId actionType:(UUIntentOrderActionType)actionType {
    ShowIndicator();
    WEAK_SELF();
    [GetIntentOrderManager() asyncUpdateIntentOrderWithOrderId:orderId price:nil actionType:actionType completeBlock:^(NSError *error) {
        HideIndicatorInView(weakSelf.view);
        
        if (error == nil) {
            [weakSelf updateOrderListForOrderId:orderId actionType:actionType];
        } else {
            ShowTipsOnView(error.localizedDescription, weakSelf.view);
        }
    }];
}

- (void)updateOrderListForOrderId:(NSNumber *)orderId actionType:(UUIntentOrderActionType)actionType {
    if (actionType == UUIntentOrderActionTypeIgnoreAll) {
        [self reload];
        return;
    }
    
    NSInteger index = NSNotFound;
    for (int i = 0; i < self.orders.count; ++i) {
        UUIntentOrderModel *order = self.orders[i];
        if ([orderId isEqual:order.id]) {
            index = i;
            break;
        }
    }
    
    if (index == NSNotFound) {
        return;
    }
    
    switch (actionType) {
        case UUIntentOrderActionTypeIgnore:
            [self.orders removeObjectAtIndex:index];
            [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]
                                  withRowAnimation:UITableViewRowAnimationAutomatic];
            if (self.orders.count == 0) {
                [self reload];
            }
            break;
        case UUIntentOrderActionTypeIgnoreAll: {
            [self.orders removeAllObjects];
            NSMutableArray<NSIndexPath *> *indexPathes = [NSMutableArray arrayWithCapacity:self.orders.count];
            for (int i = 0; i < self.orders.count; ++i) {
                [indexPathes addObject:[NSIndexPath indexPathForRow:i inSection:0]];
            }
            [self.tableView deleteRowsAtIndexPaths:indexPathes withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
        case UUIntentOrderActionTypeBid: {
            UUIntentOrderModel *order = self.orders[index];
            order.isBid = YES;
            
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]
                                  withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orders.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUIntentOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    UUIntentOrderModel *model = self.orders[indexPath.row];
    [cell setupWithModel:model];
    
    WEAK_SELF();
    [cell setConfirmBlock:^{
        [weakSelf confirmOrder:model.id];
    }];
    
    [cell setIgnoreBlock:^{
        [weakSelf ignoreOrder:model.id];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UUIntentOrderModel *model = self.orders[indexPath.row];
    
    UUIntentOrderDetailVC *orderDetailVC = [UUIntentOrderDetailVC instanceOfAppropriate];
    orderDetailVC.intentOrderId = model.id;
    [self.navigationController pushViewController:orderDetailVC animated:YES];
}

#pragma mark - UUIntentOrderManagerObserver methods

- (void)intentOrderDidUpdate:(NSNumber *)orderId withActionType:(NSNumber *)_actionType {
    UUIntentOrderActionType actionType = [_actionType integerValue];
    [self updateOrderListForOrderId:orderId actionType:actionType];
}

@end
